package UI;

import User.ScoreBoard;
import TetrisGame.Logic;
import javax.swing.*;
import java.awt.*;
import java.util.PriorityQueue;

public class MainInterface extends JFrame
{
    private Logic tetrisGame;
    private ScoreBoard scoreBoard;
    private Userinterface userInterface;
    private BackgroundMusicPlayer backgroundMusicPlayer;

    public MainInterface(Userinterface userInterface, Logic tetrisGame, ScoreBoard scoreBoard)
    {
        this.tetrisGame = tetrisGame;
        this.scoreBoard = scoreBoard;
        this.userInterface = userInterface;

        setTitle("主界面");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); //垂直排列组件

        //使用GridBagLayout布局管理器
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL; // 水平填充
        gbc.insets = new Insets(10, 10, 10, 10); //设置组件之间的间隔
        //创建按钮
        JButton gameInfoButton = new JButton("游戏说明");
        JButton startGameButton = new JButton("开始游戏");
        JButton viewLeaderboardButton = new JButton("查看排行榜");
        //添加组件到窗口中
        gbc.gridx = 0; gbc.gridy = 0; add(gameInfoButton, gbc);
        gbc.gridx = 0; gbc.gridy = 1; add(startGameButton, gbc);
        gbc.gridx = 0; gbc.gridy = 2; add(viewLeaderboardButton, gbc);

        //为按钮添加事件监听器
        gameInfoButton.addActionListener(e -> showGameInfo());
        startGameButton.addActionListener(e -> startGame());
        viewLeaderboardButton.addActionListener(e -> viewLeaderboard());

        setSize(300, 300);
        setLocationRelativeTo(null); //设置窗口居中显示
        setVisible(true);

        //初始化背景音乐播放器
        backgroundMusicPlayer = new BackgroundMusicPlayer("Music.wav");
        backgroundMusicPlayer.startMusic(); //开始播放背景音乐
    }

    private void showGameInfo()
    {
        JTextArea textArea = new JTextArea();
        textArea.setText("游戏玩法说明：\n"
                + "1. 使用←/→方向键控制方块的移动。\n"
                + "2. 使用↑方向键旋转方块。\n"
                + "3. 使用↓方向键可使方块下降一格。\n"
                + "4. 按下空格键可以快速下降。\n"
                + "5. 按C键继续；按P键暂停。\n"
                + "6. 按S键重新开始；按R键返回上一步。\n"
                + "7. 当一行被填满时，该行会消失，并且您的分数会增加。\n"
                + "8. 游戏结束的条件是当方块堆积到顶部，无法再放置新的方块时。");
        textArea.setEditable(false); //设置文本区域不可编辑
        textArea.setLineWrap(true); //设置文本自动换行
        textArea.setFont(new Font("Serif", Font.PLAIN, 18)); //设置文本区域的字体大小
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setPreferredSize(new Dimension(460, 320)); //设置滚动面板的首选大小
        JOptionPane.showConfirmDialog(this, scrollPane, "游戏说明", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
    }

    private void startGame()
    {
        String currentUsername = userInterface.getCurrentUsername(); //获取当前用户名
        tetrisGame.setCurrentUser(currentUsername); //设置当前用户
        dispose(); // 关闭登录窗口
        JFrame gameFrame = new JFrame("俄罗斯方块");
        gameFrame.add(tetrisGame);
        gameFrame.setVisible(true);
        gameFrame.setSize(815, 940);
        gameFrame.setLocationRelativeTo(null);
        gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //tetrisGame.setCurrentUser(usernameField.getText().trim()); // 确保设置当前用户
        new Thread(() -> tetrisGame.start()).start(); // 在新线程中开始游戏
    }

    private void viewLeaderboard()
    {
        // 创建一个新的对话框
        JFrame leaderboardFrame = new JFrame("排行榜");
        leaderboardFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        leaderboardFrame.setSize(300, 380);
        leaderboardFrame.setLayout(new BorderLayout());

        int fontSize = 20; //需要调整字体大小
        Font font = new Font("Serif", Font.PLAIN, fontSize);

        // 使用优先队列按分数降序排序用户名
        PriorityQueue<String> leaderboard = new PriorityQueue<>(
                (a, b) -> scoreBoard.getScore(b).compareTo(scoreBoard.getScore(a))
        );
        leaderboard.addAll(scoreBoard.getNames()); // 获取用户名集合
        DefaultListModel<String> model = new DefaultListModel<>(); //创建一个列表模型
        while (!leaderboard.isEmpty()) //添加排行榜信息
        {
            String username = leaderboard.poll(); // 取出并移除队列头部的元素（分数最高的用户）
            model.addElement(username + ": " + scoreBoard.getScore(username));
        }

        JList<String> leaderboardList = new JList<>(model); //创建一个列表并添加到滚动面板中
        leaderboardList.setFont(font); // 设置列表的字体大小
        JScrollPane scrollPane = new JScrollPane(leaderboardList);
        scrollPane.setPreferredSize(new Dimension(leaderboardFrame.getWidth(), leaderboardFrame.getHeight() - 50));
        leaderboardFrame.add(scrollPane, BorderLayout.CENTER); //添加滚动面板到对话框


        JButton closeButton = new JButton("关闭"); //添加关闭按钮
        closeButton.setFont(font); // 设置关闭按钮的字体大小
        closeButton.addActionListener(e -> leaderboardFrame.dispose()); //关闭对话框
        leaderboardFrame.add(closeButton, BorderLayout.SOUTH);

        // 设置对话框居中显示
        leaderboardFrame.setLocationRelativeTo(this);
        leaderboardFrame.setVisible(true); // 显示排行榜对话框
    }

}